import { onMounted, reactive, ref } from 'vue'
import type { CodeItem, PageQuery } from '@/type/common/list-types'
import { getViewStatementApi } from '@/api/view'

export function useList<T>(viewId: string, getData: () => void, init: () => void | Promise<void>) {
  const tableData = ref<T[]>([])
  const statement = ref<any>()
  const pageQuery = reactive<PageQuery>({ pageNum: 1, pageSize: 10, sortRules: [], filters: {} })
  const total = ref<number>(0)
  const tableLoading = ref<boolean>(false)

  onMounted(() => {
    getViewStatementApi(viewId).then((res: any) => {
      statement.value = res.data
      handleInitAndGetData().then(() => {})
    })
  })

  async function handleInitAndGetData() {
    await init()
    getData()
  }

  function search(filter: any, sortRules: any, pageNum: number) {
    pageQuery.sortRules = sortRules
    pageQuery.pageNum = pageNum
    pageQuery.filters = filter
    getData()
  }

  function hiddenColumn(column: string) {
    visible(column, false)
  }

  function showColumn(column: string) {
    visible(column, true)
  }

  function changeCodeList(column: string, codeList: CodeItem[]) {
    const find = statement.value.mateList.find((it: any) => it.property === column)
    if (find !== undefined) {
      find.codes = codeList
    }
  }

  function visible(column: string, visible: boolean) {
    const find = statement.value.mateList.find((it: any) => it.property === column)
    if (find !== undefined) {
      find.visible = visible
    }
  }

  return {
    tableData,
    pageQuery,
    statement,
    total,
    tableLoading,
    hiddenColumn,
    changeCodeList,
    showColumn,
    search
  }
}
